package com.qijian.maindata.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qijian.common.annotation.Log;
import com.qijian.common.core.controller.BaseController;
import com.qijian.common.core.domain.AjaxResult;
import com.qijian.common.core.page.TableDataInfo;
import com.qijian.common.enums.BusinessType;
import com.qijian.common.exception.ServiceException;
import com.qijian.common.utils.ObjectUtils;
import com.qijian.common.utils.mybatis.WhereEntityTool;
import com.qijian.common.utils.poi.ExcelUtil;
import com.qijian.maindata.domain.*;
import com.qijian.maindata.domain.dto.LineProcessExport;
import com.qijian.maindata.domain.query.BomDetailQuery;
import com.qijian.maindata.domain.query.LineProcessItemQuery;
import com.qijian.maindata.domain.query.LineProcessQuery;
import com.qijian.maindata.domain.vo.LineProcessDataVo;
import com.qijian.maindata.domain.vo.LineProcessVo;
import com.qijian.maindata.domain.vo.ProcessFilesVo;
import com.qijian.maindata.service.*;
import com.qijian.system.domain.User;
import com.qijian.system.service.IUserService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 工艺Controller
 *
 * @author qijian
 * @date 2021-09-03
 */
@Api(tags = "工艺管理：工艺")
@RestController
@RequiredArgsConstructor
@RequestMapping("/maindata/process")
public class LineProcessController extends BaseController {

    private final ILineProcessService lineProcessService;
    private final IBomDetailService bomDetailService;
    private final ILineProcessItemService lineProcessItemService;



    private final IUserService userService;

    private final IProcessFileViewHistoryService fileViewHistoryService;


    /**
     * 查询工艺列表
     */
    @PreAuthorize("@ss.hasPermi('maindata:line:list')")
    @GetMapping("/list")
    public TableDataInfo list(LineProcessQuery query, IPage<LineProcess> page) {
        return getDataTable(lineProcessService.page(Page.of(page.getCurrent(), page.getSize()), WhereEntityTool.invoke(query)));
    }

    @PreAuthorize("@ss.hasPermi('maindata:bom:add')")
    @PostMapping("/importProcess/{bomId}")
    public AjaxResult importData(@PathVariable("bomId") Long bomId, MultipartFile file) throws Exception {
        List<LineProcessExport> list = new ExcelUtil<>(LineProcessExport.class).importExcel(file.getInputStream());
        lineProcessService.exportProcess(bomId, list);
        return AjaxResult.success();
    }

    /**
     * 导出工艺列表
     */
    @PreAuthorize("@ss.hasPermi('maindata:line:export')")
    @Log(title = "工艺", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(LineProcessQuery query) {
        return new ExcelUtil<>(LineProcess.class).exportExcel(lineProcessService.list(WhereEntityTool.invoke(query)), "工艺数据");
    }

    /**
     * 获取工艺详细信息
     */
    @PreAuthorize("@ss.hasPermi('maindata:line:query')")
    @GetMapping(value = "/{lineId}")
    public AjaxResult getInfo(@PathVariable("lineId") Long lineId) {
        LineProcessQuery query = new LineProcessQuery();
        query.setLineId(lineId);
        List<LineProcessVo> list = lineProcessService.listAndImageVo(WhereEntityTool.invoke(query));
        BomDetailQuery bomDetailQuery = new BomDetailQuery();
        bomDetailQuery.setLineId(lineId);
        List<BomDetail> bomDetailList = bomDetailService.list(WhereEntityTool.invoke(bomDetailQuery));
        if (CollectionUtil.isNotEmpty(bomDetailList)) {
            BomDetail bomDetail = bomDetailList.get(0);
            LineProcessItemQuery processItemQuery = new LineProcessItemQuery();
            processItemQuery.setBomId(bomDetail.getDetailId());
            List<LineProcessItem> lineProcessItemList = lineProcessItemService.list(WhereEntityTool.invoke(processItemQuery));
            list.forEach(action -> {
                if ("XL".equals(action.getProcessType()) && CollectionUtil.isEmpty(action.getProcessItemList()) && CollectionUtil.isNotEmpty(lineProcessItemList)) {
                    action.setProcessItemList(lineProcessItemList);
                }
            });
        }
        return AjaxResult.success(list);
    }

    @GetMapping(value = "/bomProcess/{bomId}")
    public AjaxResult getBomProcess(@PathVariable("bomId") Long bomId) {
        BomDetailQuery query = new BomDetailQuery();
        query.setBomId(bomId);
        return AjaxResult.success(lineProcessService.selectProcessVo(WhereEntityTool.invoke(query)));
    }

    /**
     * 用户工艺线路
     *
     * @param query
     * @return
     */
    @GetMapping(value = "/earn")
    public AjaxResult getProcess(LineProcessQuery query) {
        if (ObjectUtils.isNotNull(query.getCreateId())) {
            Long createId = query.getCreateId();
            User user = userService.getById(createId);
            if (ObjectUtils.isNotEmpty(user)) {
                query.setCreateBy(user.getNickName());
                query.setCreateId(null);
            }
        }
        return AjaxResult.success(lineProcessService.selectProcessVo(WhereEntityTool.invoke(query)));
    }

    /**
     * 查询人工需求成本列表
     */
    @GetMapping("/cost/{bomId}")
    public TableDataInfo cost(@PathVariable("bomId") Long bomId, @RequestParam("isTree") Boolean isTree, @RequestParam(value = "isOut", required = false) Boolean isOut, @RequestParam(value = "typeName", required = false) String typeName) {
        return getDataTable(lineProcessService.groupByTypeName(bomId, isTree, typeName, isOut));
    }

    /**
     * 查询人工需求成本列表(不分组)
     */
    @GetMapping("/listByTypeName/{bomId}")
    public TableDataInfo listByTypeName(@PathVariable("bomId") Long bomId, @RequestParam("isTree") Boolean isTree, @RequestParam(value = "isOut", required = false) Boolean isOut, @RequestParam(value = "typeName", required = false) String typeName) {
        return getDataTable(lineProcessService.listByTypeName(bomId, isTree, typeName, isOut));
    }


    /**
     * 查询人工需求成本列表定额
     */
    @GetMapping("/listByTypeName4de/{bomId}")
    public TableDataInfo listByTypeName4de(@PathVariable("bomId") Long bomId, @RequestParam("isTree") Boolean isTree,
                                           @RequestParam("requestType") String requestType, @RequestParam(value = "isOut", required = false) Boolean isOut,
                                           @RequestParam(value = "typeName", required = false) String typeName) {

        return getDataTable(lineProcessService.listByTypeName4de(bomId, isTree, typeName, isOut,requestType));
    }

    /**
     * 替代方案
     *
     * @param processId /
     * @return /
     */
    @GetMapping(value = "/replace/{processId}")
    public AjaxResult replace(@PathVariable("processId") Long processId) {
        LineProcess lineProcess = lineProcessService.getById(processId);
        LineProcessQuery query = new LineProcessQuery();
        query.setPlanSystem(lineProcess.getPlanSystem());
        List<LineProcess> list = lineProcessService.list(WhereEntityTool.invoke(query));
        Map<String, List<LineProcess>> map = new HashMap<>();
        list.forEach(action -> {
            if (!lineProcess.getPlanCode().equals(action.getPlanCode())) {
                List<LineProcess> lineProcessList = map.get(action.getPlanCode());
                if (CollectionUtil.isEmpty(lineProcessList)) {
                    lineProcessList = new ArrayList<>(16);
                    map.put(action.getPlanCode(), lineProcessList);
                }
                lineProcessList.add(action);
            }
        });
        return AjaxResult.success(map);
    }

    @PreAuthorize("@ss.hasPermi('maindata:line:copy')")
    @GetMapping(value = "/copy/{lineId}")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult copy(@PathVariable("lineId") Long lineId) {
        lineProcessService.copy(lineId);
        return AjaxResult.success(1);
    }

    /**
     * 新增工艺
     */
    @PreAuthorize("@ss.hasPermi('maindata:line:add')")
    @Log(title = "工艺", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody List<LineProcess> lineProcesss) {
        lineProcessService.saveData(null, null, lineProcesss);
        return toAjax(1);
    }

    /**
     * 新增工艺
     */
    @PreAuthorize("@ss.hasPermi('maindata:line:add')")
    @Log(title = "工艺批量", businessType = BusinessType.INSERT)
    @PostMapping(value = "/BatchBomLine")
    public AjaxResult addBomLine(@RequestBody List<LineProcessDataVo> resources) {
        return AjaxResult.success(lineProcessService.addBatchLine(resources));
    }

    /**
     * 新增工艺
     */
    @PreAuthorize("@ss.hasPermi('maindata:line:add')")
    @Log(title = "工艺", businessType = BusinessType.INSERT)
    @PostMapping(value = "/bomLine")
    public AjaxResult addBomLine(@RequestBody LineProcessDataVo vo) {
        return AjaxResult.success(lineProcessService.saveData(vo.getBom(), vo.getLine(), vo.getLineProcesss()));
    }

    /**
     * 修改工艺
     */
    @PreAuthorize("@ss.hasPermi('maindata:line:edit')")
    @Log(title = "工艺", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult edit(@RequestBody LineProcess lineProcess) {
        return toAjax(lineProcessService.updateById(lineProcess));
    }

    @PreAuthorize("@ss.hasPermi('maindata:line:edit')")
    @Log(title = "工艺", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/editProcess")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult editProcess(@RequestBody List<LineProcess> resources) {
        if (CollUtil.isEmpty(resources)) {
            throw new ServiceException("E01:信息为空");
        }
        return toAjax(lineProcessService.editProcess(resources));
    }

    /**
     * 删除工艺
     */
    @PreAuthorize("@ss.hasPermi('maindata:line:remove')")
    @Log(title = "工艺", businessType = BusinessType.DELETE)
    @DeleteMapping("/{processIds}")
    public AjaxResult remove(@PathVariable List<Long> processIds) {
        return toAjax(lineProcessService.removeByIds(processIds));
    }

    @GetMapping(value = "/listEcnLine/{type}")
    public AjaxResult listEcnLine(@PathVariable Integer type, LineProcessQuery query) {
        return AjaxResult.success(lineProcessService.selectEcnProcessVo(query, type));
    }





    /***
     * 工艺线路批量绑定文件
     */
    @PostMapping("/batchBindFiles")
    public AjaxResult batchBindFiles(@RequestBody ProcessFilesVo filesVo){
        return AjaxResult.success(fileViewHistoryService.batchBindFiles(filesVo));
    }
    /***
     * 获取工序对应的文件列表
     */
    @GetMapping("/processBindFiles/{processId}/{wuId}")
    public AjaxResult getProcessBindFiles(@PathVariable Long processId,@PathVariable("wuId") Long wuId){
        return AjaxResult.success(fileViewHistoryService.getProcessBindFiles(processId,wuId));
    }

    /***
     * 获取工序对应的文件列表
     */
    @GetMapping("/processBindFilesById/{processId}")
    public AjaxResult processBindFilesById(@PathVariable Long processId){
        return AjaxResult.success(fileViewHistoryService.processBindFilesById(processId));
    }

    /***
     * 接单前点击文件记录留存
     */
    @PostMapping("/bindView")
    public AjaxResult bindViewHistory(@RequestBody ProcessFileViewHistory fileViewHistory){
        return AjaxResult.success(fileViewHistoryService.saveView(fileViewHistory));
    }
}
